import abc
from typing import Optional
from warnings import warn

from matplotlib import pyplot as plt

from .live_channel import InputType, LiveConsumer


class LiveFigure(LiveConsumer[InputType], abc.ABC):
    def __init__(self, figure: Optional[plt.Figure] = None):
        if not plt.isinteractive():
            warn("LinesViewer is better used in interactive mode!")

        if figure is not None:
            figure = figure
        else:
            # create figure using new_figure_manager to avoid disturbing the default figure
            new_num = max(plt.get_fignums(), default=-1) + 1
            figure_manager = plt.new_figure_manager(new_num)
            figure: plt.Figure = figure_manager.canvas.figure
            figure.show()
        figure.canvas.draw_idle()

        self._figure: plt.Figure = figure

    def send(self, data: InputType):
        self._update_gui(data)
        self.figure.canvas.draw_idle()

    @property
    def figure(self) -> plt.Figure:
        return self._figure

    @abc.abstractmethod
    def _update_gui(self, data: InputType):
        pass
